package studio.xiaoyun.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import studio.xiaoyun.core.exception.CoreException;
import studio.xiaoyun.web.HttpError;
import studio.xiaoyun.web.HttpResponse;
import studio.xiaoyun.web.HttpStatus;

/**
 * 通过web方式访问时，所有未捕获的异常都会在这里处理
 * @author 岳正灵
 * @since 1.0.0
 *
 */
public class WebExceptionInterceptor implements HandlerExceptionResolver {
    private Logger logger = LoggerFactory.getLogger(WebExceptionInterceptor.class);
	
	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception exception) {
		String message = exception.getMessage()==null?"null":exception.getMessage();
		int statusCode = HttpStatus.INTERNAL_SERVER_ERROR.value();
		if(exception instanceof CoreException){
			CoreException coreException = (CoreException)exception;
			statusCode = coreException.getErrorCode().getStatusCode().value();
			logger.info(message);
		}else{
			logger.error(message, exception);
		}
		response.setStatus(statusCode);    //设置响应的状态码
		HttpResponse httpResponse = new HttpResponse();
		HttpError httpError = new HttpError();
		httpError.setMessage(message);
		httpError.setStack(exception);
		httpResponse.setError(httpError);
		
		ModelAndView result = new ModelAndView();
		result.addObject("response", httpResponse);      //以json、xml格式返回错误信息
		result.setViewName("error/"+statusCode);  //以html格式返回错误信息
		return result;
	}

}
